package org.bichko.cydot;

import static java.lang.String.*;
import org.bichko.cydot.DotParser.*;
import java.io.*;

public abstract class AbstractParser {

    protected final DotScanner scan;
    protected Symbol symbol = null;
    protected String text = null;

    public AbstractParser(Reader reader) {
        scan = new DotScanner(reader);
    }

    public final boolean parse() {
        parseRoot();
        return true;
    }

    abstract protected void parseRoot();

    protected Symbol next() {
        try {
            symbol = scan.next();
            text = scan.getText();
            return symbol;
        } catch (IOException ioe) {
            throw new DotIoException(ioe);
        }
    }

    protected void assertState(Symbol symbol) {
        if (this.symbol != symbol)
            error();
    }

    protected void assertNext(Symbol symbol) {
        if (next() != symbol)
            error();
    }

    protected String token() {
        String token = format("[%s]", symbol);
        if (text != null)
            token = token.concat(format(" '%s'", text));
        return token;
    }

    protected void error() {
        throw new DotFormatException("unexpected token: %s", token());
    }
}
